/**
 * @Title: UserController.java
 * @Package com.lemon.controller.cityRun
 * @Description: (一句话阐述):
 * @author Ran_cc
 * @date 2018年10月17日
 * @version V1.0
 */
package com.lemon.controller.crwx;

import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import com.alibaba.fastjson.JSONObject;
import com.lemon.conf.MyException;
import com.lemon.conf.content.IdTypeHandler;
import com.lemon.conf.redis.RedisUtil;
import com.lemon.controller.BaseController;
import com.lemon.model.buy.PayUnifiedorderResult;
import com.lemon.model.cityRun.CrShopActivityOut;
import com.lemon.model.cityRun.CrShopGoods;
import com.lemon.model.cityRun.CrShopGoodsType;
import com.lemon.model.cityRun.CrShopOrderComment;
import com.lemon.model.cityRun.CrShopOrders;
import com.lemon.model.cityRun.CrShopSet;
import com.lemon.model.cityRun.CrShopTablesServer;
import com.lemon.model.cityRun.CrShopUser;
import com.lemon.model.cityRun.CrShops;
import com.lemon.model.cityRun.CrUsersInfo;
import com.lemon.service.cityRun.CrShopGoodsService;
import com.lemon.service.cityRun.CrShopOrderService;
import com.lemon.service.cityRun.CrShopUserService;
import com.lemon.service.cityRun.CrShopsService;
import com.lemon.service.cityRun.CrSysRuleService;
import com.lemon.service.cityRun.CrUserService;
import com.lemon.service.cityRun.ShopActivityService;
import com.lemon.service.cityRun.ShopTablesService;
import com.lemon.utils.IpUtils;
import com.lemon.utils.MD5;
import com.lemon.utils.PlatUtils;
import com.lemon.utils.ReqResult;
import com.lemon.utils.StringUtil;
import com.lemon.utils.TokenUtils;
import com.lemon.utils.XMLUtils;
import com.lemon.utils.pay.Constants;
import com.lemon.utils.pay.PayUtil;
import com.lemon.utils.sval.StaticValues;

import io.jsonwebtoken.Claims;

/**
 * <p>
 * Title: UserController
 * </p>
 * <p>
 * Description:
 * </p>
 * <p>
 * Company:
 * </p>
 * 
 * @author Ran_cc
 * @date 2018年10月17日
 * @版本 V 1.0
 */
@RestController
@RequestMapping("/xshop")
public class CrShopWxController extends BaseController {

	@Resource
	private CrShopsService shopService;
	@Resource
	private CrShopUserService userService;
	@Resource
	private CrUserService uService;

	@Resource
	private CrSysRuleService ruleService;

	@Resource
	private CrShopGoodsService goService;
	@Resource
	private CrShopOrderService orService;

	@Resource
	private ShopActivityService acService;

	@Resource
	private CrUserService crUserService;

	@Resource
	private ShopTablesService tabServer;

	@RequestMapping("/getShopsList")
	public ReqResult getShopsList(@ModelAttribute CrShops shop , HttpServletRequest request ,
			HttpServletResponse response) {
		ReqResult reqResult = new ReqResult();
		try {

			String ty = request.getParameter("queryType");
			String tit = shop.getShopTitle();
			StringBuffer buffer = new StringBuffer();
			//热门搜索词汇
			if (StringUtil.isNotBlank(tit)) {
				shop.setShopTitle(null);
				switch (tit) {
				case "烧烤":
					buffer.append(" and ( a.shop_title like concat('%','烧','%')");
					buffer.append("  or a.shop_title like concat('%','烤','%')");
					buffer.append("  or a.shop_title like concat('%','肉','%')");
					buffer.append("  )");
					break;
				case "海鲜":
					buffer.append(" and ( a.shop_title like concat('%','海','%')");
					buffer.append("  or a.shop_title like concat('%','鲜','%')");
					buffer.append("  )");
					break;
				case "奶茶":
					buffer.append(" and ( a.shop_title like concat('%','奶','%')");
					buffer.append("  or a.shop_title like concat('%','茶','%')");
					buffer.append("  )");
					break;
				case "火锅":
					buffer.append(" and ( a.shop_title like concat('%','火锅','%')");
					buffer.append("  )");
					break;
				case "麻辣烫":
					buffer.append(" and ( a.shop_title like concat('%','麻辣','%')");
					buffer.append("  )");
					break;
				case "米线":
					buffer.append(" and ( a.shop_title like concat('%','米线','%')");
					buffer.append("  )");
					break;
				case "鸡骨架":
					buffer.append(" and ( a.shop_title like concat('%','鸡','%')");
					buffer.append("  )");
					break;
				case "烤鱼":
					buffer.append(" and ( a.shop_title like concat('%','鱼','%')");
					buffer.append("  )");
					break;
				case "炒菜":
					buffer.append(" and ( a.shop_title like concat('%','菜','%')");
					buffer.append("  )");
					break;
				case "饺子":
					buffer.append(" and ( a.shop_title like concat('%','饺','%')");
					buffer.append("  )");
					break;
				case "包子":
					buffer.append(" and ( a.shop_title like concat('%','包子','%')");
					buffer.append("  )");
					break;
				case "汉堡":
					buffer.append(" and ( a.shop_title like concat('%','堡','%')");
					buffer.append("  )");
					break;
				case "面条":
					buffer.append(" and ( a.shop_title like concat('%','面','%')");
					buffer.append("  )");
					break;
				case "快餐":
					buffer.append(" and ( a.shop_title like concat('%','餐','%')");
					buffer.append("  )");
					break;
				default:
					shop.setShopTitle(tit);
					break;
				}
			}
			//获取系统设置的店铺离用户的距离范围
			//String json = XMLUtils.getXmlToJSONString(XMLUtils.setUrl);
			String json = RedisUtil.get(RedisUtil.key_before + "setting");
			if (StringUtil.isEmpty(json)) {
				json = XMLUtils.getXmlToJSONString(XMLUtils.setUrl);
			}
			JSONObject parse = (JSONObject) JSONObject.parse(json);
			JSONObject object = (parse.getJSONObject("sets")).getJSONObject("sysSet");
			Object object2 = object.get("distance");
			Integer sc = 0;
			if (object2 != null) {
				sc = Integer.parseInt(object2.toString());
			}
			Integer dist = sc * 1000;
			buffer.append(
					"  and a.shop_status != 0  and a.shop_status != 3  and a.shop_status != 2  and a.shop_status != 4 and a.shop_status != 5  and a.shop_status != 6  ");

			/*
			 * if (StringUtil.isNotBlank(ty)) {
			 * // buffer.append(" and f.activity_type = ");
			 * switch (ty) {
			 * case "4":
			 * //满减优惠
			 * buffer.append(
			 * " AND   IF(  (f.activity_type=2 AND f.status = 1) ,  f.activity_type IN (1,2,3)  ,  f.activity_type NOT IN (1,2,3) ");
			 * buffer.append("  AND  f.activity_type=2 OR  f.activity_type !=2 ");
			 * break;
			 * case "5":
			 * //新客立减
			 * buffer.append(
			 * " AND   IF(  (f.activity_type=1 AND f.status = 1) ,  f.activity_type IN (1,2,3)  ,  f.activity_type NOT IN (1,2,3) ");
			 * buffer.append("  AND  f.activity_type=1 OR  f.activity_type !=1 ");
			 * break;
			 * case "6":
			 * //单品折扣
			 * buffer.append(
			 * " AND   IF(  (f.activity_type=3 AND f.status = 1) ,  f.activity_type IN (1,2,3)  ,  f.activity_type NOT IN (1,2,3) ");
			 * buffer.append("  AND  f.activity_type=3 OR  f.activity_type !=3 ");
			 * break;
			 * default:
			 * break;
			 * }
			 * }
			 * buffer.append(" AND f.status = 1");
			 * buffer.append(" AND f.activity_type_obj = 1");
			 * buffer.append(" AND f.activity_type IN (1,2,3)");
			 */
			boolean flag = false;
			String shopIdsAct = "";
			List<String> shopIdList = new ArrayList<String>();
			ty = StringUtil.isEmpty(ty) ? "1" : ty;
			if (StringUtil.isNotBlank(ty)) {
				// buffer.append(" and f.activity_type = ");
				CrShopActivityOut ou = new CrShopActivityOut();
				ou.setShopId(shop.getId());
				ou.setPageNum(shop.getPageNum());
				ou.setPageSize(shop.getPageSize());
				String tt2 = "";
				if (ty.indexOf(",") >= 0 || "4".equals(ty) || "5".equals(ty) || "6".equals(ty)) {
					String[] split = ty.split(",");
					for (int i = 0; i < split.length; i++) {
						String tt = split[i];
						switch (tt) {
						case "4":
							tt2 += "2,";
							break;
						case "5":
							tt2 += "1,";
							break;
						case "6":
							tt2 += "3,";
							break;
						default:
							break;
						}
					}
					ou.setWhere(" and a.Activity_Type in (" + tt2.substring(0 , tt2.length() - 1) + ") ");
				}
				shopIdList.addAll(acService.selectDisShopIdsByType(ou));

				String[] tyL = ty.split("-");
				if (tyL.length > 0) {
					String tys = tyL[0];
					String[] split = tys.split(",");
					for (int i = 0; i < split.length; i++) {
						switch (split[i]) {
						case "4":
							//满减优惠 查询带有此活动的商铺id
							ou.setActivityType(2);
							shopIdList.addAll(acService.selectDisShopIdsByType(ou));
							if (!flag) {
								flag = true;
							}
							break;
						case "5":
							//新客立减
							ou.setActivityType(1);
							shopIdList.addAll(acService.selectDisShopIdsByType(ou));
							if (!flag) {
								flag = true;
							}
							break;
						case "6":
							//单品折扣
							ou.setActivityType(3);
							shopIdList.addAll(acService.selectDisShopIdsByType(ou));
							if (!flag) {
								flag = true;
							}
							break;
						default:
							break;
						}
					}
				}

			}

			if (shopIdList != null && shopIdList.size() > 0) {
				for (int i = 0; i < shopIdList.size(); i++) {
					shopIdsAct += shopIdList.get(i);
					if ((1 + i) < shopIdList.size()) {
						shopIdsAct += ",";
					}
				}
				if (flag) {
					buffer.append(" AND a.id in (" + shopIdsAct + ")");
				}
			}
			//全部显示所有商家, 如果需要根据距离来显示,则设置为true
			if (false) {
				if (dist != null && dist > 0) {
					buffer.append(" HAVING distance < " + dist
							+ " AND (a.shop_send_distance * 1000) > distance  and a.shop_send_distance > 0 ");
				} else {
					buffer.append(" HAVING  (a.shop_send_distance * 1000) > distance  and a.shop_send_distance > 0  ");
				}
			} else {
				buffer.append(" and a.shop_send_distance > 0  ");
			}

			StringBuffer order = new StringBuffer();
			order.append("order by ");
			if (StringUtil.isNotBlank(ty)) {
				String[] tyL = ty.split("-");
				if (tyL.length >= 1) {
					String tys = tyL[0];
					switch (tys) {
					case "1":
						//距离最近
						order.append(" distance asc  ");
						break;
					case "11":
						//销量最高
						order.append(" orderCount desc ");
						break;
					case "12":
						//起送价最低
						order.append(" shop_send_minprice asc  ");
						break;
					case "13":
						//销量最高
						order.append(" distance asc  ");
						break;
					case "2":
						order.append(" distance asc  ");
						break;
					case "3":
						//好评优先
						order.append(" avgStar desc , orderCount desc  ");
						break;
					default:
						order.append(" distance asc  ");
						break;
					}
				}

			}
			shop.setWhere(buffer.toString());
			if (shop.getShopType() != null && shop.getShopType() != 0) {
				shop.setWhereAppend(" and a.shop_type = ?" , shop.getShopType());
			}
			shop.setWhereAppend(" and a.server_end_time  > ? " , StringUtil.DateToString(new Date() , 0));
			//			shop.setLongitude("119.958444");
			//			shop.setLatitude("30.266561");
			//查询管理员列表
			shop.setOrderBy(order.toString());
			List<CrShops> list = shopService.selectxListBySelective(shop);
			reqResult.setReturnResult(list);
		} catch (Exception e) {
			reqResult.setReturnResult("" , ReqResult.code_error);
			MyException.writeErr(e , "查询客户或管理员列表失败");
		}
		return reqResult;
	}

	@RequestMapping("/getShopById")
	public ReqResult getShopById(@ModelAttribute CrShops shop , HttpServletRequest request ,
			HttpServletResponse response) {
		ReqResult reqResult = new ReqResult();
		try {
			//CrShopUser u = (CrShopUser) request.getSession().getAttribute("user");
			//			long ri = IdTypeHandler.decode(u.getRuleId());
			//			if (ri == 0 || ri == 2) {
			//				reqResult.setReturnResult("权限不足" , ReqResult.code_no_permission);
			//				return reqResult;
			//			}
			//			if (u.getUserType() == 1) {
			//				CrShops list = shopService.selectShopAndUserBySel(shop);
			//				if (list.getShopInCharge() != null && list.getShopInCharge() != 0) {
			//					list.setShopInCharge(list.getShopInCharge() / 100);
			//				}
			//			shop.setLongitude("119.958444");
			//			shop.setLatitude("30.266561");
			List<CrShops> list = shopService.selectxListBySelective(shop);
			CrShops cs = null;
			if (list.size() > 0) {
				cs = list.get(0);
			}

			CrShops shops = shopService.selectShopAndAtvByPrimaryKey(shop.getId());

			if (cs != null && shops != null) {
				String[] splits = shops.getShopSendPrice().split(",");
				if (0 != shops.getShopSendDistance() && StringUtil.isNotBlank(splits[0])) {
					for (int j = 0; j < splits.length; j++) {
						String[] split = splits[j].split("-");
						int shopDis = cs.getDistance();
						if (shopDis >= 1000 * Double.parseDouble(split[0])
								&& shopDis <= 1000 * Double.parseDouble(split[1])) {
							shops.setShopSendPrice(split[2]);
							break;
						} else {
							if (shopDis > 1000 * Double.parseDouble(split[1])) {
								shops.setShopSendPrice(split[2]);
							}
						}
					}
				} else {
					shops.setShopSendPrice("0");
				}
			} else {
				if (StringUtil.isNotBlank(shops.getShopSendPrice())) {
					String[] splits = shops.getShopSendPrice().split(",");
					String[] split = splits[0].split("-");
					shops.setShopSendPrice(split[2]);
				}
			}
			if (shops.getShopSendPrice().split("-").length > 1) {
				String[] splits = shops.getShopSendPrice().split(",");
				String[] split = splits[0].split("-");
				shops.setShopSendPrice(split[2]);
			}
			//判断是否是此店铺新客
			String string = request.getParameter("wxUserId");
			if (StringUtil.isNotBlank(string)) {
				CrShopOrders o = new CrShopOrders();
				o.setShopId(shop.getId());
				o.setUserId(string);
				o.setType(1);
				int i = orService.selectCountBySelective(o);
				if (i > 0) {
					shop.setIsNewUser("n");
				} else {
					shop.setIsNewUser("y");
				}
			}
			if (StringUtil.isEmpty(shops.getShopSendPrice())) {
				shops.setShopSendPrice("0");
			}
			//处理活动
			String actType = request.getParameter("actType");
			if (StringUtil.isNotBlank(actType)) {
				List<CrShopActivityOut> atList = shops.getAtList();
				List<CrShopActivityOut> atList2 = null;
				if (atList != null && atList.size() >= 0) {
					atList2 = new ArrayList<CrShopActivityOut>();
					for (int i = 0; i < atList.size(); i++) {
						CrShopActivityOut out = atList.get(i);
						if ("1".equals(actType)) {
							// 123
							Integer type = out.getActivityType();
							if (type < 4) {
								atList2.add(out);
							}
						} else if ("2".equals(actType)) {
							Integer type = out.getActivityType();
							if (type >= 4) {
								atList2.add(out);
							}
						}
					}
					shops.setAtList(atList2);
				}
			}

			shops.setAvgStar(cs.getAvgStar()); //平均分
			shops.setOrderCount(cs.getOrderCount());
			CrShopUser user = userService.selectById(cs.getShopUserId());
			shops.setUserContact(user.getUserContact());
			shops.setIsNewUser(shop.getIsNewUser());

			reqResult.setReturnResult(shops);
			//			}
		} catch (Exception e) {
			reqResult.setReturnResult("" , ReqResult.code_error);
			MyException.writeErr(e , "查询客户或管理员列表失败");
		}
		return reqResult;
	}

	@RequestMapping("/getShopByWxUserId")
	public ReqResult getShopByWxUserId(String wxUserId , HttpServletRequest request , HttpServletResponse response) {
		ReqResult reqResult = new ReqResult();
		try {
			//先查询数据是否有当前小程序绑定的账户信息
			String token = request.getHeader("wxToken");
			log.info("微信端下单:wxToken={}" , token);
			String openId = "";
			if (StringUtil.isNotBlank(token)) {
				Claims parseJWT = TokenUtils.parseJWT(token);
				String info = parseJWT.getId();
				log.info("解析后的token={}" , info);
				if (StringUtil.isNotBlank(info)) {
					String[] split = info.split("\\|");
					openId = split[0];
				}
				log.info("解析后的openId={}" , openId);
				if (StringUtil.isEmpty(openId)) {
					reqResult.setReturnResult("token is null " , ReqResult.code_no_permission);
					return reqResult;
				}
			} else {
				reqResult.setReturnResult("token is null " , ReqResult.code_no_permission);
				return reqResult;
			}

			//如果数据库没有  查询redis 缓存 , 如果缓存也没有就显示空 让小程序添加
			CrShops cs = new CrShops();
			cs.setWhere(" and b.user_wx = ? " , openId);
			cs.setOrderBy(" order by a.create_time desc");
			CrShops css = shopService.selectShopAndUserBySel(cs);
			if (css == null) {
				String string = RedisUtil.get(RedisUtil.key_before + "newShop:" + wxUserId);
				if (StringUtil.isEmpty(string)) {
					reqResult.setReturnResult("");
					return reqResult;
				} else {
					reqResult.setReturnResult(JSONObject.parse(string));
					return reqResult;
				}
			} else {
				if (css.getShopStatus() < 4 && css.getShopStatus() > 0) {
					JSONObject js = new JSONObject();
					js.put("account" , css.getUserAccount());
					js.put("shopStatus" , css.getShopStatus());
					js.put("pwd" , "abc123456");
					js.put("url" , "https://www.chengpao8.com/cityRun/adm/index.html");
					js.put("picUrl" , "http://cpimg.chengpao8.cn/5fdbfc0fbc3749bcb654de041e5badbc.jpg");
					reqResult.setReturnResult(js);
					return reqResult;
				}
				reqResult.setReturnResult(css);
				return reqResult;
			}

		} catch (Exception e) {
			reqResult.setReturnResult("" , ReqResult.code_error);
			MyException.writeErr(e , "查询客户或管理员列表失败");
		}
		return reqResult;
	}

	//商品分类//////////////////////////////////////////////////////

	/**
	 * <b>Description:<blockquote> 获取分类列表
	 * </blockquote></b>
	 * 
	 * @Title: getGoodsTypeList
	 * @param gt
	 * @param request
	 * @param response
	 * @return
	 * @author Ran_cc
	 * @date 2018年10月23日
	 */
	@RequestMapping("/getGoodsTypeList")
	public ReqResult getGoodsTypeList(@ModelAttribute CrShopGoodsType gt , HttpServletRequest request ,
			HttpServletResponse response) {
		ReqResult reqResult = new ReqResult();
		try {
			gt.setWhere(" and status != 0 ");
			gt.setOrderBy(" order by sort asc");
			List<CrShopGoodsType> list = goService.selectTypeListBySelective(gt);
			reqResult.setReturnResult(list);
		} catch (Exception e) {
			MyException.writeErr(e , "");
		}
		return reqResult;
	}

	/**
	 * <b>Description:<blockquote> 获得店铺商品列表
	 * </blockquote></b>
	 * 
	 * @Title: getGoodsList
	 * @param go
	 * @param request
	 * @param response
	 * @return
	 * @author Ran_cc
	 * @date 2018年11月9日
	 */
	@RequestMapping("/getGoodsList")
	public ReqResult getGoodsList(@ModelAttribute CrShopGoods go , HttpServletRequest request ,
			HttpServletResponse response) {
		ReqResult reqResult = new ReqResult();
		try {
			if (StringUtil.isEmpty(go.getGoodsTypeId()) || "0".equals(go.getGoodsTypeId())) {
				go.setGoodsTypeId(null);
			}
			go.setWhere(" and a.status = 1 ");
			if (StringUtil.isNotBlank(go.getGoodsSupport())) {
				go.setWhereAppend(" and a.Goods_Support like concat('%',?,'%')" , go.getGoodsSupport());
				go.setGoodsSupport(null);
			}

			go.setOrderBy(" order by a.sort asc");
			List<CrShopGoods> list = goService.selectwxListBySelective(go);
			reqResult.setReturnResult(list);
		} catch (Exception e) {
			MyException.writeErr(e , "");
		}
		return reqResult;
	}

	/**
	 * <b>Description:<blockquote> 获得店铺商品列表
	 * </blockquote></b>
	 * 
	 * @Title: getGoodsList
	 * @param go
	 * @param request
	 * @param response
	 * @return
	 * @author Ran_cc
	 * @date 2018年11月9日
	 */
	@RequestMapping("/getShopGoodsByOrder")
	public ReqResult getShopGoodsByOrder(@ModelAttribute CrShopGoods go , HttpServletRequest request ,
			HttpServletResponse response) {
		ReqResult reqResult = new ReqResult();
		try {
			String gids = request.getParameter("goodsIds");
			String ids = "";
			if (StringUtil.isNotBlank(gids)) {
				String[] split = gids.split(",");
				for (int i = 0; i < split.length; i++) {
					String sp = split[i];
					ids += IdTypeHandler.decode(sp);
					if ((i + 1) < split.length) {
						ids += ",";
					}
				}
			}
			go.setWhere(" and a.id in (" + ids + ")");
			List<CrShopGoods> list = goService.selectwxListBySelective(go);
			reqResult.setReturnResult(list);
		} catch (Exception e) {
			MyException.writeErr(e , "");
		}
		return reqResult;
	}

	/**
	 * <b>Description:<blockquote> 获得店铺商品列表
	 * </blockquote></b>
	 * 
	 * @Title: getGoodsList
	 * @param go
	 * @param request
	 * @param response
	 * @return
	 * @author Ran_cc
	 * @date 2018年11月9日
	 */
	@RequestMapping("/getGoodsById")
	public ReqResult getGoodsById(@ModelAttribute CrShopGoods go , HttpServletRequest request ,
			HttpServletResponse response) {
		ReqResult reqResult = new ReqResult();
		try {
			if (StringUtil.isEmpty(go.getGoodsTypeId()) || "0".equals(go.getGoodsTypeId())) {
				go.setGoodsTypeId(null);
			}
			List<CrShopGoods> list = goService.selectwxListBySelective(go);
			reqResult.setReturnResult(list.size() > 0 ? list.get(0) : null);
		} catch (Exception e) {
			MyException.writeErr(e , "");
		}
		return reqResult;
	}

	/**
	 * <b>Description:<blockquote> 获得店铺评价列表
	 * </blockquote></b>
	 * 
	 * @Title: getGoodsList
	 * @param go
	 * @param request
	 * @param response
	 * @return
	 * @author Ran_cc
	 * @date 2018年11月9日
	 */
	@RequestMapping("/getShopsCommentList")
	public ReqResult getShopsCommentList(@ModelAttribute CrShopOrderComment comment , HttpServletRequest request ,
			HttpServletResponse response) {
		ReqResult reqResult = new ReqResult();
		try {
			comment.setWhere(" and a.status != 0 and  a.status != 2 and b.shop_id = ? " ,
					IdTypeHandler.decode(comment.getShopId()));
			comment.setOrderBy(" order by a.create_time desc");
			List<CrShopOrderComment> list = orService.selectCommentsListBySelective(comment);
			reqResult.setReturnResult(list);
		} catch (Exception e) {
			MyException.writeErr(e , "");
		}
		return reqResult;
	}

	/**
	 * <b>Description:<blockquote> 新增管理员信息
	 * </blockquote></b>
	 * 
	 * @Title: addAdminUserInfo
	 * @param user
	 * @param request
	 * @param response
	 * @return
	 * @author Ran_cc
	 * @date 2018年10月18日
	 */
	@RequestMapping(value = "/payAddShopInfo")
	public ReqResult payAddShopInfo(@ModelAttribute CrShops shop , HttpServletRequest request ,
			HttpServletResponse response) {
		ReqResult reqResult = new ReqResult();
		try {
			String wxUserId = request.getParameter("userId");
			String token = request.getHeader("wxToken");
			log.info("微信端商家入驻支付:wxToken={}" , token);
			String openId = "";
			if (StringUtil.isNotBlank(token)) {
				Claims parseJWT = TokenUtils.parseJWT(token);
				String info = parseJWT.getId();
				log.info("解析后的token={}" , info);

				if (StringUtil.isNotBlank(info)) {
					String[] split = info.split("\\|");
					openId = split[0];
				}
				log.info("解析后的openId={}" , openId);
				if (StringUtil.isEmpty(openId)) {
					reqResult.setReturnResult("token is null " , ReqResult.code_no_permission);
					return reqResult;
				}
			}
			String orderNo = StringUtil.createSerialNoCityRun();
			String ip = IpUtils.getIpAddr(request);
			CrShops shops = RedisUtil.get(RedisUtil.key_before + "newShop:" + wxUserId , CrShops.class);
			log.info("获取redis中的申请入驻的商家的信息:{}" , shops);
			PayUnifiedorderResult result = PayUtil.createrOrder(Constants.WeChatAPPID , openId , "城跑 - 入驻支付" ,
					shops.getShopInCharge() , orderNo , ip , Constants.pay_notify_url_ruzhu , wxUserId);
			if (result != null) {
				result.setOrderNo(orderNo);
			}
			reqResult.setReturnResult(result);
			return reqResult;
		} catch (Exception e) {
			reqResult.setReturnResult("" , ReqResult.code_error);
			MyException.writeErr(e , "查询客户或管理员列表失败");
		}
		return reqResult;
	}

	/**
	 * <b>Description:<blockquote> 新增管理员信息
	 * </blockquote></b>
	 * 
	 * @Title: addAdminUserInfo
	 * @param user
	 * @param request
	 * @param response
	 * @return
	 * @author Ran_cc
	 * @date 2018年10月18日
	 */
	@RequestMapping(value = "/addShopInfo.do")
	public ReqResult addShopInfo(@ModelAttribute CrShops shop , HttpServletRequest request ,
			HttpServletResponse response) {
		ReqResult reqResult = new ReqResult();
		try {

			String token = request.getHeader("wxToken");
			log.info("微信端商家入驻支付:wxToken={}" , token);
			String openId = "";
			if (StringUtil.isNotBlank(token)) {
				Claims parseJWT = TokenUtils.parseJWT(token);
				String info = parseJWT.getId();
				log.info("解析后的token={}" , info);

				if (StringUtil.isNotBlank(info)) {
					String[] split = info.split("\\|");
					openId = split[0];
				}
				log.info("解析后的openId={}" , openId);
				if (StringUtil.isEmpty(openId)) {
					reqResult.setReturnResult("token is null " , ReqResult.code_no_permission);
					return reqResult;
				}
			}
			//			CrShopUser acc = userService.selectShopUserByAcc(shop.getUserAccount());
			CrShops cs = new CrShops();
			cs.setWhere(
					" and (shop_status = 1 or  shop_status =2 or  shop_status = 3 )  and b.user_account = ? " ,
					shop.getUserAccount());
			CrShops acc = shopService.selectShopAndUserBySel(cs);
			if (acc != null) {
				reqResult.setReturnResult("当前手机号已存在" , ReqResult.code_exist);
				return reqResult;
			}
			CrUsersInfo ci = new CrUsersInfo();
			ci.setWxOpenId(openId);
			List<CrUsersInfo> cis = uService.selectListBySelective(ci);
			int price = 0;
			String string = RedisUtil.get(RedisUtil.key_before + "setting");
			JSONObject parse = (JSONObject) JSONObject.parse(string);
			JSONObject js = parse.getJSONObject("sets");
			JSONObject js2 = js.getJSONObject("sysSet");
			Date serv = null;
			Calendar c = Calendar.getInstance();
			c.setTime(new Date());
			if (shop.getShopType() == 1) {
				if ("0".equals(js2.get("freeDay1").toString())) {
					price = Integer.parseInt(js2.get("firstYear1").toString());
					c.add(Calendar.YEAR , 1);//利用Calendar 实现 Date日期+1天  
					serv = c.getTime();
				} else {
					c.add(Calendar.DAY_OF_MONTH , Integer.parseInt(js2.get("freeDay1").toString()));//利用Calendar 实现 Date日期+1天  
					serv = c.getTime();
				}
			} else {
				if ("0".equals(js2.get("freeDay2").toString())) {
					price = Integer.parseInt(js2.get("firstYear2").toString());
					c.add(Calendar.YEAR , 1);//利用Calendar 实现 Date日期+1天  
					serv = c.getTime();
				} else {
					c.add(Calendar.DAY_OF_MONTH , Integer.parseInt(js2.get("freeDay2").toString()));//利用Calendar 实现 Date日期+1天  
					serv = c.getTime();
				}
			}
			String wxUserId = request.getParameter("userId");
			shop.setShopStatus(7);
			shop.setUserWx(openId);
			shop.setShopInCharge(price);
			shop.setServerEndTime(serv);
			String locationByAddress = PlatUtils.getLocationByAddress(shop.getAddressInfo());
			shop.setAddressLocation(locationByAddress);
			log.info("微信端入驻商家需要支付:{}分" , price);
			if (price > 0) {
				//返回支付信息
				//调用微信支付
				String orderNo = StringUtil.createSerialNoCityRun();
				String ip = IpUtils.getIpAddr(request);
				RedisUtil.set(RedisUtil.key_before + "newShop:" + wxUserId , shop , 1 * 24 * 60 * 60);
				PayUnifiedorderResult result = PayUtil.createrOrder(Constants.WeChatAPPID , openId , "城跑 - 入驻支付" ,
						price , orderNo , ip , Constants.pay_notify_url_ruzhu , wxUserId);
				if (result != null) {
					result.setOrderNo(orderNo);
				}
				reqResult.setReturnResult(result);
				return reqResult;
			} else if (price == 0) {
				CrShops s = new CrShops();
				s.setAddressArea(shop.getAddressArea());
				s.setAddressProvince(shop.getAddressProvince());
				s.setAddressCity(shop.getAddressCity());
				s.setAddressInfo(shop.getAddressInfo());

				if (!StringUtil.isNotBlank(shop.getLatitude()) || !StringUtil.isNotBlank(shop.getLongitude())) {
					if (StringUtil.isNotBlank(locationByAddress)) {
						s.setLongitude(locationByAddress.split(",")[0]);
						s.setLatitude(locationByAddress.split(",")[1]);
					}
				} else {
					s.setLongitude(shop.getLongitude());
					s.setLatitude(shop.getLatitude());
				}
				s.setServerEndTime(serv);
				s.setShopLicense(shop.getShopLicense());
				s.setShopLogo(shop.getShopLogo());
				s.setShopStatus(4);
				s.setShopType(shop.getShopType());
				s.setShopTitle(shop.getShopTitle());
				s.setShopInCharge(shop.getShopInCharge());

				CrShopUser u = new CrShopUser();
				u.setRuleId(IdTypeHandler.encode(StaticValues.RULE_ID_SHOP_USER));
				u.setUserAccount(shop.getUserAccount());
				//				if (StringUtil.isEmpty(shop.getUserPwd())) {
				//					String pwd = shop.getUserContact().substring(shop.getUserContact().length() - 6 ,
				//							shop.getUserContact().length());

				//					u.setUserPwd(MD5.getMD5(pwd));
				//				}
				u.setUserPwd(MD5.getMD5("abc123456"));
				u.setUserCardBack(shop.getUserCardBack());
				u.setUserCardFront(shop.getUserCardFront());
				u.setUserContact(shop.getUserContact());
				u.setUserType(2);
				u.setUserWx(openId);
				u.setUserWxName(cis.get(0).getNickName());
				u.setUserStatus(0);
				u.setUserName(shop.getUserName());
				u.setUserIdCard(shop.getUserIdCard());
				int i = shopService.insertShopsAndSUserInfo(u , s);
			}
			reqResult.setReturnResult(1);

		} catch (Exception e) {
			reqResult.setReturnResult("" , ReqResult.code_error);
			MyException.writeErr(e , "查询客户或管理员列表失败");
		}
		return reqResult;
	}

	/**
	 * <b>Description:<blockquote> 微信获取店铺入驻的时长移机费用
	 * </blockquote></b>
	 * 
	 * @Title: getTimePSet
	 * @param request
	 * @param response
	 * @return
	 * @author Ran_cc
	 * @date 2018年11月19日
	 */
	@RequestMapping(value = "/getTimePSet")
	public ReqResult getTimePSet(int type , HttpServletRequest request , HttpServletResponse response) {
		ReqResult reqResult = new ReqResult();
		try {

			/*
			 * String jsonString = XMLUtils.getXmlToJSONString(XMLUtils.setUrl);
			 * JSONObject parse = (JSONObject) JSONObject.parse(jsonString);
			 * JSONObject js = parse.getJSONObject("sets").getJSONObject("sysSet");
			 */

			String string = RedisUtil.get(RedisUtil.key_before + "setting");
			JSONObject js = ((JSONObject) JSONObject.parse(string)).getJSONObject("sets").getJSONObject("sysSet");

			JSONObject jss = new JSONObject();
			if (type == 1) {
				if (StringUtil.isNotBlank(js.getString("freeDay1")) && !"0".equals(js.getString("freeDay1"))) {
					jss.put("time" , js.getString("freeDay1"));
					jss.put("price" , "0");
				} else {
					jss.put("time" , "1");
					jss.put("price" , js.getString("firstYear1"));
				}
			} else {
				if (StringUtil.isNotBlank(js.getString("freeDay2")) && !"0".equals(js.getString("freeDay2"))) {
					jss.put("time" , js.getString("freeDay2"));
					jss.put("price" , "0");
				} else {
					jss.put("time" , "1");
					jss.put("price" , js.getString("firstYear2"));
				}
			}
			jss.put("phone" , js.get("platPhone"));
			reqResult.setReturnResult(jss);
		} catch (Exception e) {
			reqResult.setReturnResult("" , ReqResult.code_error);
			MyException.writeErr(e , "设置系统平台基本信息");
		}
		return reqResult;
	}

	@RequestMapping("/getShopSetBySID")
	public ReqResult getShopSetBySID(@ModelAttribute CrShopSet shop , HttpServletRequest request ,
			HttpServletResponse response) {
		ReqResult reqResult = new ReqResult();
		try {
			String string = RedisUtil.get("cityRun:set:set_" + shop.getShopId());
			if (StringUtil.isNotBlank(string) && !"null".equals(string)) {
				CrShops cs = shopService.selectShopById(shop.getShopId());
				JSONObject parse = (JSONObject) JSONObject.parse(string);
				if (!StringUtil.isNotBlank(parse.get("payTypeOut"))) {
					parse.put("payTypeOut" , cs.getPayTypeOut());
				}
				reqResult.setReturnResult(parse);
				return reqResult;
			}
			CrShopSet set = shopService.selectShopSetByShopId(shop);
			if (null == set && StringUtil.isNotBlank(shop.getShopId())) {
				//添加一条信息的设置信息
				CrShops cs = shopService.selectShopById(shop.getShopId());
				shopService.insertShopSetInfo(shop);
				shop.setPayTypeOut(cs.getPayTypeOut());
				set = shop;
				RedisUtil.set("cityRun:set:set_" + shop.getShopId() , set);
			} else {
				RedisUtil.set("cityRun:set:set_" + shop.getShopId() , set);
			}
			reqResult.setReturnResult(set);
		} catch (Exception e) {
			reqResult.setReturnResult("" , ReqResult.code_error);
			MyException.writeErr(e , "查询客户或管理员列表失败");
		}
		return reqResult;
	}

	//新增呼叫服务

	@RequestMapping("/addTableServer")
	public ReqResult addTableServer(@ModelAttribute CrShopTablesServer server , HttpServletRequest request ,
			HttpServletResponse response) {
		ReqResult reqResult = new ReqResult();
		try {
			server.setStatus(1);
			server.setTitle(server.getTitle());
			int row = tabServer.insertTableServer(server);
		} catch (Exception e) {
			reqResult.setReturnResult("" , ReqResult.code_error);
			MyException.writeErr(e , "查询客户或管理员列表失败");
		}
		return reqResult;
	}

	public static void main(String[] args) {
		String jsonString = XMLUtils.getXmlToJSONString(XMLUtils.setUrl);
		JSONObject parse = (JSONObject) JSONObject.parse(jsonString);
		JSONObject js = parse.getJSONObject("sets").getJSONObject("sysSet");
		System.out.println(js.toJSONString());
	}
}
